/**
 * 首页 create to by doujiabao - 20191210
 */

import React, { Component } from 'react'

import styles from './index.module.styl'

import axios from 'axios'
import moment from 'moment'
import api from '@/services/api'

import Page from '@/components/Page'
import Navigation from '@/components/Navigation'
import { Modal, Button, Input, message } from 'antd'

const { confirm } = Modal
const { TextArea } = Input

class Home extends Component {

    state = {
        //ws对象
        ws: {},
        //消息列表
        message: {},
        //我想说
        sayVal: '',
    }

    componentDidMount() {
        // 打开一个WebSocket:
        var ws = new WebSocket('ws://39.106.181.25:9091')

        this.setState({ ws: ws })

        // 响应onmessage事件:
        ws.onmessage = (msg) => {

            axios.get(api.getMessage)
                .then((res) => {
                    this.setState({
                        message: {
                            ...res.data,
                            data: res.data.data.reverse()
                        }
                    })
                })
                .catch((err) => {
                });

        };

        // 响应onclose事件:
        ws.onclose = (msg) => {
            message.error('断开连接')
        };
    }

    say = () => {
        const _this = this
        confirm({
            title: '你想说？',
            content: <TextArea onChange={(e) => {
                _this.setState({ sayVal: e.currentTarget.value })
            }} placeholder="请输入" autoSize={{ minRows: 3, maxRows: 5 }} />,
            onOk() {
                return axios.get(api.say, {
                    params: {
                        user_account: 'music',
                        user_name: 'musicbaby',
                        user_message: _this.state.sayVal ? _this.state.sayVal : '←这个玩家什么也没说',
                        send_time: moment().unix(),
                    }
                }).then((res) => {
                    _this.state.ws.send('客户端')

                    message.success('朕已收到你的消息')
                }).catch((err) => {
                    message.error('可能是接口挂了')
                });
            },
            onCancel() { }
        });
    }

    render() {

        const {
            message = {}
        } = this.state

        const {
            data = []
        } = message

        return (<Page
            fetched={true}
            fetching={false}
        >

            <Navigation />

            <div className={styles.what}>
                <Button onClick={this.say}>我想说</Button>
            </div>

            <div className={styles.message}>
                {data.map((itm, idx) => (<div key={idx}>
                    <em>{moment(+itm.send_time * 1000).format('YYYY-MM-DD HH:mm')}</em>
                    <p>匿名：{itm.user_message}</p>
                </div>))}

                <span className={styles.bottom}>啊客官...到底了呢</span>
            </div>

        </Page>)
    }

}

export default Home